package main

import (
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

// 返回静态页面
func handleIndex(writer http.ResponseWriter, request *http.Request) {
	t, _ := template.ParseFiles("index.html")
	t.Execute(writer, nil)
}

type viewHandler struct{}

//http://127.0.0.1:8080/?path=/Users/wangchuanyi/speak/6.1.mp4
//http://127.0.0.1:8080/testGet
func (vh *viewHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Query().Get("path")

	data, err := ioutil.ReadFile(string(path))
	fmt.Println("read size of mp4", len(data))
	if err != nil {
		log.Printf("Error with path %s: %v", path, err)
		w.WriteHeader(404)
		w.Write([]byte("404"))
	}

	if strings.HasSuffix(path, ".html") {
		w.Header().Add("Content-Type", "text/html")
	} else if strings.HasSuffix(path, ".mp4") {
		w.Header().Add("Content-Type", "video/mp4")
		//Content-Type，内容类型，一般是指网页中存在的Content-Type，
		//用于定义网络文件的类型和网页的编码，决定浏览器将以什么形式、什么编码读取这个文件，

	}

	w.Write(data)
}

// 处理GET请求
func handleGet(writer http.ResponseWriter, request *http.Request) {
	query := request.URL.Query()

	// 第一种方式
	// id := query["id"][0]

	// 第二种方式
	id := query.Get("id")

	fmt.Printf("GET: id=%s\n", id)

	fmt.Fprintf(writer, `{"code":0}`)
}

func main() {
	//http://127.0.0.1:8080/
	http.HandleFunc("/", handleIndex)
	http.Handle("/readmp4", new(viewHandler))
	http.HandleFunc("/testGet", handleGet)
	http.ListenAndServe(":8080", nil)
}
